package com.longrise.android.byjk.plugins.publicWeb;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.longrise.android.byjk.R;
import com.longrise.common.base.BaseActivity;
import com.longrise.android.byjk.event.PublicWebEvent;
import com.longrise.common.utils.DeviceUtils;
import com.longrise.common.utils.NetUtil;
import com.longrise.android.byjk.widget.view.BaseFrameView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by callxkj on 2017/3/7.
 * 用来显示第三方页面,比如一些没有交互的页面
 * 现在包括的页面有,新手专区,首页跳转到外部页面
 */

public class PublicWebActivity extends BaseActivity<PublicWebPresenter> implements BaseFrameView.ReloadListener,
        PublicWebContract.View {
    private static final String TAG = "PublicWebActivity";
    public static String FROM_PAGE = "from_page";
    public static String PAGE_NAME = "PublicWebActivity";
    public static String TITLE = "title"; //标题
    public static String URL = "url"; //webview加载链接
    public static String BACK_TYPE = "backtype"; //toolbar返回样式 两种:BACK_ARROW ,BACK_FORK
    public static String BACK_ARROW = "backarrow"; //返回的样式是箭头
    public static String BACK_FORK = "fork"; // 返回的样式是叉叉

    private String mBack_type = BACK_ARROW;
    private Toolbar mToolbar;
    private BaseFrameView mBfv;
    private WebView mWv;
    private String mTitle;
    private WebSettings webSettings;
    private String mFirstUrl;
    private boolean mLoadError = false;
    private String mUrl;
    private boolean mIsCurrentPage = true;


    @Override
    public int getContentViewId(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_publicweb;
    }

    @Override
    public void initView() {
        mIsCurrentPage = true;
        mToolbar = (Toolbar) findViewById(R.id.byjk_toolbar);
        mToolbar.setTitle("");
        setSupportActionBar(mToolbar);
        mBfv = (BaseFrameView) findViewById(R.id.publicweb_bfv);
        mWv = (WebView) findViewById(R.id.publicweb_wv);
        initWebView();
        initData();
        initEvent();
        EventBus.getDefault().register(this);
    }

    /**
     * 初始化webview
     */
    private void initWebView() {
        webSettings = mWv.getSettings();
        mWv.clearHistory();
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setUseWideViewPort(true);
        // 设置WebView属性，能够执行Javascript脚本
        webSettings.setJavaScriptEnabled(true);
        //设置 缓存模式 不用缓存 使用localStorage
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webSettings.setDomStorageEnabled(true);
        webSettings.setAppCacheMaxSize(1024 * 1024 * 8);
        String absolutePath = mContext.getApplicationContext().getCacheDir().getAbsolutePath();
        webSettings.setAppCachePath(absolutePath);
        webSettings.setAllowFileAccess(true);
        webSettings.setAppCacheEnabled(true);
        webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        mWv.setWebViewClient(new PublicWebClient());
        mWv.setWebChromeClient(new PublicWebChromeClient());
        mWv.addJavascriptInterface(mPresenter, "bb"); //交互放到presenter
    }

    private void initData() {
        Intent intent = getIntent();
        mTitle = intent.getStringExtra(TITLE);
        mFirstUrl = intent.getStringExtra(URL);
        mBack_type = intent.getStringExtra(BACK_TYPE);
        mUrl = mFirstUrl;
        if (BACK_FORK.equals(mBack_type)) { //通过传过来的type判断标题是显示叉叉还是箭头
            mToolbar.setNavigationIcon(R.drawable.umeng_by_ic_close_black);
        } else {
            mToolbar.setNavigationIcon(R.drawable.ic_back_main);
        }
        setWebTitle(mTitle);
        toLoadUrl(mFirstUrl);
    }

    private void initEvent() {
        mBfv.setOnReloadListener(this);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (BACK_FORK.equals(mBack_type)) {  //如果是叉叉 直接关闭
                    finish();
                } else {
                    if (mWv.canGoBack()) {
                        mWv.goBack();
                    } else {
                        close();
                    }
                }
            }
        });
    }

    /**
     * 加载网页
     */
    private void toLoadUrl(String url) {
        if (checkNetwork() && mWv != null) {
            mWv.loadUrl(url);
        }
    }

    /**
     * 检查是否有网络
     *
     * @return
     */
    private boolean checkNetwork() {
        if (!NetUtil.checkNetEnable()) {
            loadError();
            return false;
        } else {
            return true;
        }
    }

    /**
     * 开始加载
     */
    private void loadStart() {
        if (mIsCurrentPage) {
            mBfv.setLoadingStatus(BaseFrameView.LoadingStatus.LOADING);
            mBfv.setVisibility(View.VISIBLE);
            mWv.setVisibility(View.GONE);
        }
    }

    /**
     * 加载成功
     */
    private void loadSuccess() {
        Disposable subscribe = Observable.timer(200, TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        mBfv.setLoadingStatus(BaseFrameView.LoadingStatus.SUCCESS);
                        mBfv.setVisibility(View.GONE);
                        if (mWv != null) {
                            mWv.setVisibility(View.VISIBLE);
                        }
                        mLoadError = false;
                    }
                });
        mRxmanager.addDisposable(subscribe);
    }

    /**
     * 加载失败
     */
    private void loadError() {
        if (mIsCurrentPage) {
            mBfv.setLoadingStatus(BaseFrameView.LoadingStatus.ERROR);
            mBfv.setVisibility(View.VISIBLE);
            mWv.setVisibility(View.GONE);
            mLoadError = true;
        }
    }

    /**
     * 加载失败后 点击屏幕重新加载
     */
    @Override
    public void onReload(View v) {
        mLoadError = false;
        toLoadUrl(mUrl);
    }

    /**
     * 监控返回键
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && mWv.canGoBack()) {
            if (mWv.canGoBack()) {
                mWv.goBack();
            } else {
                close();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (mWv != null) {
            webSettings.setJavaScriptEnabled(false);
            mWv.clearHistory();
            mWv.destroy();
        }
    }

    @Override
    public void setWebTitle(String title) {
        mToolbar.setTitle(title);
    }

    @Override
    public void close() {
        mIsCurrentPage = false;
        finish();
    }

    @Override
    public void jumpToActivity(String title, Bundle bundle) {
        PublicWebJumpUtil.jumpToActivity(this, title, bundle);
    }

    @Override
    public void googleTracker() {
        mWv.post(new Runnable() {
            @Override
            public void run() {
                mWv.loadUrl("javascript:setDeviceInfoForGA('" + DeviceUtils.getVersionName() + "')");
            }
        });
    }

    private class PublicWebClient extends WebViewClient {

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
            mLoadError = true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            loadStart();
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            mUrl = url;
            if (mLoadError) {
                loadError();
            } else {
                loadSuccess();
            }
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    }

    private class PublicWebChromeClient extends WebChromeClient {

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            if ((!TextUtils.isEmpty(title)) && title.toLowerCase().contains("error")) {
                mLoadError = true;
            }
        }

        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            return super.onJsAlert(view, url, message, result);
        }
    }

    /**
     * 公共处理当前页面的一些事件 通过Category来区分
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void toHandlePublicWebEvent(PublicWebEvent event) {
        PublicWebEvent.Category category = event.getCategory();
        switch (category) {
            case JFRW:
                toLoadUrl(mFirstUrl); // 刷新积分任务
                break;
        }
    }

}
